import InboundPlanApi from '../../../common/api/breed/inboundplan.api.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import doT from '../../../../vendor/template/doT.js';

(function (window, document, $) {
    let _vm;
    let openId = Utils.GetSessionStorage('openId');
    let id = '';

    $(async function () {
        id = getUrlKey('id');

        _vm = new Vue({
            el: '#addentryrgst-form',
            data() {
                return {};
            },
            mounted() {
                if (id) {
                    document.title = '其他车辆入厂 - 编辑';
                    $('#btnSaveSubmit').css('display', 'none');
                } else {
                    $('#btnSaveSubmit').css('display', 'block');
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        await initSelectValue();
        if (id) {
            _ediCommand();
        }
        clickFun();
    });

    // 编辑操作
    const _ediCommand = async () => {
        if (Utils.IsNotNull(id)) {
            $('title').text('其他车辆入厂-编辑');
            await InboundPlanApi.getDetailPerInPlan(id).then((result) => {
                let otherCar = result.otherCar;
                $('#destFarm').setSelectValue(result.destFarm.id, result.destFarm.name);
                $('#planDate').val(moment(result.planDate).format('YYYY-MM-DD'));
                $('#carType').setSelectValue(otherCar.typeEnum);
                $('#carNo').val(otherCar.carNo);
                $('#times').val(otherCar.times);
                $('#driverName').val(otherCar.driverName);
                $('#driverPhone').val(otherCar.driverPhone);
            });
        }
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            history.go(-1);
        });

        // 保存
        $('#btnSave').on('click', async function (e) {
            savetips(1);
        });

        // 保存并提交
        $('#btnSaveSubmit').on('click', function (e) {
            savetips(2);
        });

        // 选择日期
        $('#search-planDate').on('click', function () {
            pickPlanDate();
        });
    };
    // 保存
    const savetips = (type = 1) => {
        let tipsInfo = type == 2 ? '是否确认保存并提交该单据？' : '是否确认保存该单据？';
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry">${tipsInfo}</div></div></div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '确定',
                    onClick: function () {
                        $.closeModal();
                        let params = {
                            type: 5, // 其他车辆入厂
                            destFarm: {
                                id: $('#destFarm').val(),
                                name: $('#destFarm').select2('data')[0]?.text,
                            },
                            otherCar: {
                                typeEnum: $('#carType').val(),
                                typeName: $('#carType').select2('data')[0]?.text,
                                carNo: $('#carNo').val(),
                                times: $('#times').val(),
                                driverName: $('#driverName').val(),
                                driverPhone: $('#driverPhone').val(),
                            },
                            planDate: $('#planDate').val(),
                            deliverySeq: 0,
                            person: null,
                            materials: null,
                            car: null,
                            remark: '',
                            billStatus: 1, // 保存传1 保存并提交传2
                        };
                        if (!Utils.IsNotNull(params.destFarm.id)) {
                            return $.toptip(`请选择农厂!`, 'warning');
                        }
                        if (!Utils.IsNotNull(params.planDate)) {
                            return $.toptip(`请选择入厂时间!`, 'warning');
                        }
                        if (!Utils.IsNotNull(params.otherCar.times)) {
                            return $.toptip(`请输入次数!`, 'warning');
                        }
                        // if (!Utils.IsNotNull(params.otherCar.driverName)) {
                        //     return $.toptip(`请输入司机姓名!`, 'warning');
                        // }
                        // if (!Utils.IsNotNull(params.otherCar.driverPhone)) {
                        //     return $.toptip(`请输入电话号码!`, 'warning');
                        // }
                        // 电话号码
                        const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;
                        if (Utils.IsNotNull(params.otherCar.driverPhone) && !PHONE_VERIFICATION.test(params.otherCar.driverPhone)) {
                            return $.toptip(`请输入正确的电话号码`, 'warning');
                        }

                        if (!Utils.IsNotNull(params.otherCar.typeEnum)) {
                            return $.toptip(`请选择车辆类型!`, 'warning');
                        }

                        if (!Utils.IsNotNull(params.otherCar.carNo)) {
                            return $.toptip(`请输入车牌号!`, 'warning');
                        }
                        // 保存
                        if (type == 1) {
                            if (id) {
                                InboundPlanApi.editEntryplans(id, params).then(
                                    (res) => {
                                        $.toptip('其他车辆入厂计划保存成功！', 'success');
                                        setTimeout(function () {
                                            location.href = `./othercarplanlist.html`;
                                        }, 1000);
                                    },
                                    (err) => {
                                        $.toptip(err.responseJSON?.msg, 'error');
                                    },
                                );
                            } else {
                                InboundPlanApi.addEntryplans(params).then(
                                    (res) => {
                                        $.toptip('其他车辆入厂计划保存成功！', 'success');
                                        setTimeout(function () {
                                            location.href = `./othercarplanlist.html`;
                                        }, 1000);
                                    },
                                    (err) => {
                                        $.toptip(err.responseJSON?.msg, 'error');
                                    },
                                );
                            }
                        }
                        // 保存并提交
                        else if (type == 2) {
                            params.billStatus = 2;
                            if (id) {
                                InboundPlanApi.editEntryplans(id, params).then(
                                    (res) => {
                                        $.toptip('其他车辆入厂计划保存提交成功！', 'success');
                                        setTimeout(function () {
                                            location.href = `./othercarplanlist.html`;
                                        }, 1000);
                                    },
                                    (err) => {
                                        $.toptip(err.responseJSON?.msg, 'error');
                                    },
                                );
                            } else {
                                InboundPlanApi.addEntryplans(params).then(
                                    (res) => {
                                        $.toptip('其他车辆入厂计划保存提交成功！', 'success');
                                        setTimeout(function () {
                                            location.href = `./othercarplanlist.html`;
                                        }, 1000);
                                    },
                                    (err) => {
                                        $.toptip(err.responseJSON?.msg, 'error');
                                    },
                                );
                            }
                        }
                    },
                },
            ],
        });
    };

    // 时间选择器
    const pickPlanDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                $('#planDate').val(result.map((item) => item.value).join('-'));
            },
        });
    };
    //TODO :初始化下拉框内容
    const initSelectValue = async () => {
        // 获取所有猪厂
        await InboundPlanApi.getSubdata('LIVESTOCK-FARMS').then((res) => {
            let info = JSON.parse(res);
            $('#destFarm')
                .empty()
                .select2({
                    placeholder: '请选择农厂...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: info.map((item) => {
                        return {
                            id: item.Id,
                            text: `${item.Name}`,
                            name: item.Name,
                        };
                    }),
                });
            $('#destFarm').setSelectValue();
        });
        // 车辆类型
        await InboundPlanApi.getSubdata('LIVESTOCK-CARTYPE').then((res) => {
            let carTypeArr = JSON.parse(res);
            $('#carType').empty().select2({
                placeholder: '请选择车辆类型...', //默认文字提示
                language: 'zh-CN', //汉化
                allowClear: true, //允许清空
                data: carTypeArr,
            });
            $('#carType').setSelectValue();
        });
    };

    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
})(window, document, jQuery);
